package com.szl.group.config.auth.custom;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 验证码  表单提交有用 暂时不用
 */
public class CustomAuthenticationProvider extends DaoAuthenticationProvider {


    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String code = req.getParameter("code");
        String verify_code = (String) req.getSession().getAttribute("verify_code");

        if (StringUtils.isBlank(code)) {
            throw new AuthenticationServiceException("验证码不能为空!");
        }
        if (StringUtils.isBlank(verify_code)) {
            throw new AuthenticationServiceException("验证码失效，请重新获取验证码!");
        }
        if (!code.toLowerCase().equals(verify_code.toLowerCase())) {
            throw new AuthenticationServiceException("验证码错误!");
        }

        super.additionalAuthenticationChecks(userDetails, authentication);
    }
}
